import { createRouter, createWebHistory } from 'vue-router'
import Layout from "@/views/layout/index.vue"
import store from "@/store"

export const routes=[
  {
    path:"/login",
    name:"login",
    label:"登录",
    hidden:true,//不参与菜单栏显示
    component:()=>import("../views/login/index.vue")
  },
  {
    path:"/403",
    name:"no-permission",
    label:"403",
    hidden:true,//不参与菜单栏显示
    component:()=>import("../views/error/no-permission.vue")
  },
  {
    path:"/layout",
    name:"layout",
    label:"首页",
    //避免../../，可以使用@符号，代表src目录
    component:Layout
  },
  {
    path:"/banner",
    name:"banner",
    label:"轮播图管理",
    component:Layout,
    children:[
      {
        path:"list",
        name:"banner/list",
        label:"轮播图列表",
        component:()=>import("@/views/banner/List.vue"),
      },
      {
        path:"add",
        name:"banner/add",
        label:"轮播图添加",
        component:()=>import("@/views/banner/Add.vue"),
      },
    ]
  },
  {
    path:"/maneger",
    name:"maneger",
    label:"管理员管理",
    component:Layout,
    children:[
      {
        path:"list",
        name:"maneger/list",
        label:"管理员列表",
        component:()=>import("@/views/maneger/List.vue"),
      }
    ]
  }
]
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  //把整个数组抽出来，便于首页列表循环
  routes:routes, /* [
    {
      path:"/login",
      name:"login",
      component:()=>import("../views/login/index.vue")
    },
    {
      path:"/",
      name:"alyout",
      //避免../../，可以使用@符号，代表src目录
      component:Layout
    },
    {
      path:"/banner",
      name:"banner",
      component:Layout,
      children:[
        {
          path:"list",
          name:"banner/list",
          component:()=>import("@/views/banner/List.vue"),
        },
        {
          path:"add",
          name:"banner/add",
          component:()=>import("@/views/banner/Add.vue"),
        },
      ]
    },
    {
      path:"/maneger",
      name:"maneger",
      component:Layout,
      children:[
        {
          path:"list",
          name:"maneger/list",
          component:()=>import("@/views/maneger/List.vue"),
        }
      ]
    }
  ] */
})

//定义一个数组，数组中的每一项是一个路由的name的值，配置在这个路由中的
//路由name，代表不需要校验登录
const whiteList=["login","no-permission"]

router.beforeEach((to,from,next)=>{
  const name=to.name
  if(whiteList.includes(name)){
    next()
  }else{
    //不存在需要校验登录
    const token=localStorage.getItem("token")
    if(token){
      //登陆了
      //next()
      //登录了再判断要去的路由是否有权限
      if(store.state.role===2||store.state.pageRoles.includes(name)){
        //有权限，放行
        next()
      }else{
        next("/403")
      }

    }else{
      ///需要重定向到login
      next({name:"login"})
    }
  }
})

export default router


/*
*顶层路由：
    /login      views/Login,vue
    /           views/Layout.vue
      /banner/list
      /banner/add

      /maneger/list
*/    
